package cn.wolfcode.trip.base.service.impl;


import cn.wolfcode.trip.base.domain.Sign;

import cn.wolfcode.trip.base.mapper.SignMapper;

import cn.wolfcode.trip.base.query.SignQueryObject;
import cn.wolfcode.trip.base.service.ISignService;

import cn.wolfcode.trip.base.util.JSONResult;
import cn.wolfcode.trip.base.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class SignServiceImpl implements ISignService {
    @Autowired
    private SignMapper signMapper;

    private SignQueryObject qo=new SignQueryObject();


    /**
     * 保存签到功能
     * @param entity
     */

    public void saveOrUpdate(Sign entity) {


        if(entity.getId()==null&&!querySigns(qo).contains(entity.getDate())){
            entity.setUser(UserContext.getUserAttribute());
            //查出现有的积分
            Integer point = signMapper.selectUserPoint(entity.getUser().getId());
            if(entity.getState()==1) {
                entity.setPoint(point +20);
            }
            Integer state = queryState(entity);
            entity.setDate(entity.getDate());
            entity.setState(state);
            signMapper.insert(entity);
        }else{
            entity.setUser(UserContext.getUserAttribute());
            signMapper.updateByPrimaryKey(entity);
        }
    }

    public List querySigns(SignQueryObject qo) {
        return signMapper.selectSigns(qo);
    }

    public Integer queryCount(SignQueryObject qo) {
        return signMapper.selectDays(qo);
    }


    /**
     * 更新积分
     *
     */
    public JSONResult updataPoint(Sign entity) {
        //查出现有的积分
        JSONResult result=new JSONResult();
        String maxDate = signMapper.selectMaxDate(entity);
        entity.setDate(maxDate);

        Integer point = signMapper.selectPointByUserId(entity);
        //已有的积分加上传来的积分
        if(point+entity.getPoint()<0){
            result.mark("积分不足");
            return result;
        }else {
            entity.setPoint(point + entity.getPoint());
            signMapper.updateByUserId(entity);
        }
        return result;
    }

    public Integer queryState(Sign entity) {
        return signMapper.selectState(entity);
    }

    //查询用户积分
    @Override
    public Integer getUserPoint(Long userId) {
        return signMapper.selectUserPoint(userId);
    }

    //购买成功后扣除商品所需积分
    @Override
    public void deletePoint(Long userId, Long productIntegral) {
        Integer point = signMapper.selectUserPoint(userId);
        if (productIntegral!=null) {
            point = point - productIntegral.intValue();
            String date = signMapper.selectMaxDateByUserId(userId);
            signMapper.updatePoint(userId, point,date);
        }
    }
}
